//
// Created by htlin on 2021/3/2 0002.
//

#include "Runnable.h"
#include <iostream>

class RunnablePrivateData {
public:
    bool autoDelete;
    Runnable::FinishedCallBack finishedCallBack;
    void *userData;
};

void Runnable::run() {

}

void Runnable::finish(bool isCancel) {
  if (isCancel) {
    std::cout << "task is cancel" << std::endl;
  }
}

void Runnable::runCB(uv_work_t *data) {
  auto thisPointer = static_cast<Runnable *>(data->data);
  thisPointer->run();
}

Runnable::Runnable() {
  data = std::unique_ptr<RunnablePrivateData>(new RunnablePrivateData());
  data->autoDelete = true;
}

void Runnable::setAutoDelete(bool autoDelete) {
  data->autoDelete = autoDelete;
}

bool Runnable::getAutoDelete() const {
  return data->autoDelete;
}

void Runnable::finishCB(uv_work_t *data, int status) {
  auto thisPointer = static_cast<Runnable *>(data->data);
  thisPointer->finish(UV_ECANCELED == status);

  if (thisPointer->data->finishedCallBack) {
    thisPointer->data->finishedCallBack(data, thisPointer->data->userData);
  }

  free(data);
  if (thisPointer->getAutoDelete()) {
    delete thisPointer;
  }
}

void Runnable::setFinishedCallBack(FinishedCallBack finishCallBack, void *userData) {
  data->finishedCallBack = finishCallBack;
  data->userData = userData;
}

Runnable::~Runnable() = default;

